package com.zyy.Household_expenditure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyy.Household_expenditure.entity.HomeBill;
import com.zyy.Household_expenditure.entity.vo.CountVo;
import com.zyy.Household_expenditure.mapper.HomeBillMapper;
import com.zyy.Household_expenditure.service.HomeBillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyy.Household_expenditure.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
@Slf4j
public class HomeBillServiceImpl extends ServiceImpl<HomeBillMapper, HomeBill> implements HomeBillService {

    /**
     * 个人账单展示
     *
     * @param request
     * @return
     */
    @Override
    public List<HomeBill> getBillByUid(HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        QueryWrapper<HomeBill> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", id);
        List<HomeBill> homeBills = baseMapper.selectList(wrapper);
        return homeBills;
    }

    /**
     * 分页个人账单查条件询展示
     *
     * @param request
     * @param current
     * @param limit
     * @param homeBill
     * @return
     */
    @Override
    public Map fyGetBillByUid(HttpServletRequest request, long current, long limit, HomeBill homeBill) {
        Page<HomeBill> homeBillPage = new Page<>(current, limit);
        String uid = JwtUtils.getMemberIdByJwtToken(request);
        QueryWrapper<HomeBill> wrapper = new QueryWrapper<HomeBill>();
        //        查uid下所有
        wrapper.eq("uid", uid)
                .orderByAsc("gmt_create", "gmt_modified");
//        //金额区间查询
        if (!StringUtils.isEmpty(homeBill.getUid())
                && !StringUtils.isEmpty(homeBill.getPriceStart())
                && !StringUtils.isEmpty(homeBill.getPriceEnd())) {
                    wrapper.between("money", homeBill.getPriceStart(), homeBill.getPriceEnd())
                    .orderByAsc("gmt_create", "gmt_modified");
        }
        //根据类型查
        if (!StringUtils.isEmpty(homeBill.getType()) &&
                !StringUtils.isEmpty(homeBill.getUid())) {
                    wrapper.eq("type", homeBill.getType())
                    .orderByAsc("gmt_create", "gmt_modified");
        }
//        创建日期查
        if (!StringUtils.isEmpty(homeBill.getUid()) &&
                !StringUtils.isEmpty(homeBill.getStatementDate())) {
                    wrapper.eq("statement_date", homeBill.getStatementDate())
                    .orderByAsc("gmt_create", "gmt_modified");
        }
//                //金额区间查询
//                .or(i -> i.between(HomeBill::getMoney, homeBill.getPriceStart(), homeBill.getPriceEnd())
//                        .and(i2 -> i2.eq(!StringUtils.isEmpty(homeBill.getUid()),
//                                HomeBill::getUid,
//                                uid)))
//
//
//                //根据类型查
//                .or(i -> i.eq(!StringUtils.isEmpty(homeBill.getType()),
//                                HomeBill::getType,
//                                homeBill.getType()
//                        )
//                        .and(i2 -> i2.eq(!StringUtils.isEmpty(homeBill.getUid()),
//                                HomeBill::getUid,
//                                uid)))
//
////                根据日期查
//                .or(i -> i.eq(!StringUtils.isEmpty(homeBill.getStatementDate()),
//                                HomeBill::getStatementDate,
//                                homeBill.getStatementDate()
//                        )
//                        .and(i2 -> i2.eq(!StringUtils.isEmpty(homeBill.getUid()),
//                                HomeBill::getUid,
//                                uid)));

        IPage<HomeBill> homeBillIPage = baseMapper.selectPage(homeBillPage, wrapper);
        long total = homeBillIPage.getTotal();
        List<HomeBill> records = homeBillIPage.getRecords();
        Map map = new HashMap();
        map.put("total", total);
        map.put("rows", records);
        return map;

    }

    /**
     * 分页个人账单查条询展示
     *
     * @param request
     * @param current
     * @param limit
     * @return
     */
    @Override
    public Map fyByUid(HttpServletRequest request, long current, long limit) {
        Page<HomeBill> homeBillPage = new Page<>(current, limit);
        String uid = JwtUtils.getMemberIdByJwtToken(request);
        QueryWrapper<HomeBill> wrapper = new QueryWrapper<>();
        QueryWrapper<HomeBill> uid1 = wrapper.eq("uid", uid);
        baseMapper.selectPage(homeBillPage, uid1);
        long total = homeBillPage.getTotal();
        List<HomeBill> records = homeBillPage.getRecords();
        Map map = new HashMap();
        map.put("total", total);
        map.put("rows", records);
        return map;
    }


    /**
     * 按月为单位，统计用户某种消费类型的消费总额
     */
    @Override
    public List<CountVo> getMenBillTypeMonth(HttpServletRequest request, String month) {
        List<CountVo> list = new ArrayList<>();
        String id = JwtUtils.getMemberIdByJwtToken(request);//用户id

        QueryWrapper<HomeBill> wrapperType = new QueryWrapper<>();
        wrapperType.eq("uid", id);
        List<HomeBill> homeBills1 = baseMapper.selectList(wrapperType);// 拿到表list

//        stream流把list中的某个属性转为Set对象
        Set<String> collect = homeBills1.stream().map(HomeBill::getType).collect(Collectors.toSet());
        String[] myArray = new String[collect.size()];
        String[] strings = collect.toArray(myArray);

        for (int voi = 0; voi < strings.length; voi++) {
            CountVo entity = new CountVo();
//            查询
            QueryWrapper<HomeBill> wrapper = new QueryWrapper<>();
            wrapper.eq("uid", id);
            wrapper.eq("type", strings[voi]);
//            查时间
            wrapper.apply(" date_format(statement_date,'%y%mm%') = date_format('" + month + "-01','%y%mm%')");//这个鸡巴用法我以后再看看
            //  一共多少钱
            List<HomeBill> homeBills = baseMapper.selectList(wrapper);

//            Integer money = 0; //对钱进行初始化
//            for (int i = 0; i < homeBills.size(); i++) {
//                money += homeBills.get(i).getMoney();
//            }
            Integer collect1 = homeBills.stream().collect(Collectors.summingInt(HomeBill::getMoney));
            entity.setType(strings[voi]);
            entity.setValue(collect1);
            list.add(entity);
        }
        return list;
    }


    /**
     * 按周为单位，统计用户某种消费类型的消费总额
     */
    @Override
    public List<CountVo> getMenBillTypeWeek(HttpServletRequest request, String week, String month) {

        List<CountVo> list = new ArrayList<>();
        String id = JwtUtils.getMemberIdByJwtToken(request);//用户id

        QueryWrapper<HomeBill> wrapperType = new QueryWrapper<>();
        wrapperType.eq("uid", id);
        List<HomeBill> homeBills1 = baseMapper.selectList(wrapperType);// 拿到表list

//        stream流把list中的某个属性转为Set对象
        Set<String> collect = homeBills1.stream().map(HomeBill::getType).collect(Collectors.toSet());
        String[] myArray = new String[collect.size()];
        String[] strings = collect.toArray(myArray);

        for (int voi = 0; voi < strings.length; voi++) {
            CountVo entity = new CountVo();
//            查询
            QueryWrapper<HomeBill> wrapper = new QueryWrapper<>();
            wrapper.eq("uid", id);
            wrapper.eq("type", strings[voi]);
//            查时间
            wrapper.apply(" date_format(statement_date,'%y%mm%') = date_format('" + month + "-01','%y%mm%')");//这个鸡巴用法我以后再看看
//
            List<HomeBill> homeBills = baseMapper.selectList(wrapper);
            String testDate = "yyyy-MM-dd";      //待增加初值
            String testDate2 = "yyyy-MM-dd";      //待增加初值
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //日期格式化工具类实例化创建
            Calendar calendar = Calendar.getInstance(); //日历时间工具类实例化创建，取得当前时间初值
            Calendar calendar2 = Calendar.getInstance(); //日历时间工具类实例化创建，取得当前时间初值
            List<Date> nowDate = homeBills.stream().map(HomeBill::getStatementDate).collect(Collectors.toList());
            Date date = nowDate.get(0);
            calendar.setTime(date);  //覆盖掉当前时间
            calendar2.setTime(date);  //覆盖掉当前时间
            int i2 = Integer.parseInt(week);
            int day = i2 * 7;
            int beforeDay = day - 7;//[beforeDay,day] 查这个区间
            calendar.add(Calendar.DATE, day); //+7
            calendar2.add(Calendar.DATE, beforeDay);

            testDate = sdf.format(calendar.getTime()); //转换回字符串
            testDate2 = sdf.format(calendar2.getTime()); //转换回字符串
            try {
                Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(testDate); //转回date
                Date beforeDay2 = new SimpleDateFormat("yyyy-MM-dd").parse(testDate2); //转回date

                System.out.println(homeBills.stream().filter(s -> s.getStatementDate().compareTo(beforeDay2) == 0));
                System.out.println("beforeDay2" + beforeDay2);
                System.out.println(date2);

                //            现在查出来是具体哪个月的数据 要通过月变成详细第几周

                //                date1.compareTo(date2)>0  Date1 时间在 Date2 之后
                //                date1.compareTo(date2)<0  Date1 时间在 Date2 之前
//                    如果两个日期相等，则返回值为0
                List<HomeBill> homeBills2 = homeBills
                        .stream()                       //查出的时间在n周乘7天之前，  并且    在n周乘7天-7天之后
                        .filter(s -> s.getStatementDate().compareTo(date2) < 0 && s.getStatementDate().compareTo(beforeDay2) >= 0)//【n，n+1】周
                        .collect(Collectors.toList());

                System.out.println("+" + homeBills);
                System.out.println(homeBills2);

                Integer collect1 = homeBills2.stream().collect(Collectors.summingInt(HomeBill::getMoney));

                entity.setType(strings[voi]);
                entity.setValue(collect1);
                list.add(entity);
            } catch (Exception e) {
            }
        }
        return list;
    }


}
